package com.yic.module.mes.controller.admin.plan;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.yic.module.base.api.factory.FactoryApi;
import com.yic.module.base.api.factory.dto.FactoryRespDTO;
import com.yic.module.base.api.item.ItemApi;
import com.yic.module.base.api.item.dto.ItemRespDTO;
import com.yic.module.base.api.workshop.WorkshopApi;
import com.yic.module.base.api.workshop.dto.WorkshopRespDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.yic.framework.common.pojo.PageResult;
import com.yic.framework.common.pojo.CommonResult;
import static com.yic.framework.common.pojo.CommonResult.success;

import com.yic.framework.excel.core.util.ExcelUtils;

import com.yic.framework.operatelog.core.annotations.OperateLog;
import static com.yic.framework.operatelog.core.enums.OperateTypeEnum.*;

import com.yic.module.mes.controller.admin.plan.vo.*;
import com.yic.module.mes.dal.dataobject.plan.PlanDO;
import com.yic.module.mes.convert.plan.PlanConvert;
import com.yic.module.mes.service.plan.PlanService;

@Tag(name = "管理后台 - 生产计划")
@RestController
@RequestMapping("/mes/plan")
@Validated
public class PlanController {

    @Resource
    private PlanService planService;
    @Resource
    private ItemApi itemApi;
    @Resource
    private FactoryApi factoryApi;
    @Resource
    private WorkshopApi workshopApi;

    @PostMapping("/create")
    @Operation(summary = "创建生产计划")
    @PreAuthorize("@ss.hasPermission('mes:plan:create')")
    public CommonResult<Long> createPlan(@Valid @RequestBody PlanCreateReqVO createReqVO) {
        return success(planService.createPlan(createReqVO));
    }

    @PostMapping("/sync")
    @Operation(summary = "同步生产计划")
    @PreAuthorize("@ss.hasPermission('mes:plan:create')")
    public CommonResult<Long> syncPlan(@Valid @RequestBody PlanSyncReqVO syncReqVO) {
        return success(planService.syncPlan(syncReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新生产计划")
    @PreAuthorize("@ss.hasPermission('mes:plan:update')")
    public CommonResult<Boolean> updatePlan(@Valid @RequestBody PlanUpdateReqVO updateReqVO) {
        planService.updatePlan(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除生产计划")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:plan:delete')")
    public CommonResult<Boolean> deletePlan(@RequestParam("id") Long id) {
        planService.deletePlan(id);
        return success(true);
    }

    @PostMapping("/cancel")
    @Operation(summary = "撤销生产计划")
    @PreAuthorize("@ss.hasPermission('mes:plan:delete')")
    @OperateLog(type = DELETE)
    public CommonResult<Boolean> cancelPlan(@RequestBody PlanCancelReqVO reqVO) {
        planService.deletePlan(reqVO.getCode());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得生产计划")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:plan:query')")
    public CommonResult<PlanRespVO> getPlan(@RequestParam("id") Long id) {
        PlanDO plan = planService.getPlan(id);
        PlanRespVO respVO = PlanConvert.INSTANCE.convert(plan);
        // 组装产品生产信息
        ItemRespDTO item = itemApi.getItem(respVO.getItemId());
        if (ObjectUtil.isNotEmpty(item) && ObjectUtil.isNotEmpty(respVO)) {
            respVO.setItemCode(item.getCode());
            respVO.setItemName(item.getName());
            respVO.setSpec(item.getSpec());
            respVO.setDrawCode(item.getDrawCode());
        }
        return success(respVO);
    }

    @GetMapping("/list")
    @Operation(summary = "获得生产计划列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('mes:plan:query')")
    public CommonResult<List<PlanRespVO>> getPlanList(@RequestParam("ids") Collection<Long> ids) {
        List<PlanDO> list = planService.getPlanList(ids);
        return success(PlanConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得生产计划分页")
    @PreAuthorize("@ss.hasPermission('mes:plan:query')")
    public CommonResult<PageResult<PlanRespVO>> getPlanPage(@Valid PlanPageReqVO pageVO) {
        PageResult<PlanDO> pageResult = planService.getPlanPage(pageVO);
        PageResult<PlanRespVO> resp = PlanConvert.INSTANCE.convertPage(pageResult);
        resp.getList().forEach(planRespVO -> {
            //封装工厂信息
            FactoryRespDTO factory = factoryApi.getFactory(planRespVO.getFactoryId());
            if (ObjectUtil.isNotEmpty(factory)) {
                planRespVO.setFactoryName(factory.getName());
            }
            //封装生产车间
            WorkshopRespDTO workshop = workshopApi.getWorkshop(planRespVO.getWorkshopId());
            if (ObjectUtil.isNotEmpty(workshop)) {
                planRespVO.setWorkshopName(workshop.getName());
            }
            //封装产品信息
            ItemRespDTO item = itemApi.getItem(planRespVO.getItemId());
            if (ObjectUtil.isNotEmpty(item)) {
                planRespVO.setItemName(item.getName());
                planRespVO.setItemCode(item.getCode());
                planRespVO.setSpec(item.getSpec());
                planRespVO.setDrawCode(item.getDrawCode());
            }
        });
        return success(resp);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出生产计划 Excel")
    @PreAuthorize("@ss.hasPermission('mes:plan:export')")
    @OperateLog(type = EXPORT)
    public void exportPlanExcel(@Valid PlanExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<PlanDO> list = planService.getPlanList(exportReqVO);
        // 导出 Excel
        List<PlanExcelVO> datas = PlanConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "生产计划.xls", "数据", PlanExcelVO.class, datas);
    }

}
